<template>
	<view class="px-2 py-4">
		<form-component :formFields="formFields" :formData="formData" :formRules="formRules" :fileLists="fileLists"
			:startUserSelectTasks="startUserSelectTasks" :startUserSelectAssignees="startUserSelectAssignees"
			:startUserSelectAssigneesFormRules="startUserSelectAssigneesFormRules" :detailId="detailId"
			:resubmit="resubmit" @submitForm="submitForm" @cancelForm="cancelForm" />
	</view>
</template>

<script setup lang="ts">
import {
	onLoad
} from "@dcloudio/uni-app";
import { ref, reactive, nextTick } from 'vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { getAccessToken } from '@/utils/auth'
import * as DefinitionApi from '@/api/bpm/definition'
import * as UserApi from '@/api/system/user'
import * as VehicleInCity from '@/api/oa/vehicleout/inCity'
import { useMessage, useToast } from 'wot-design-uni'
import { useUserStore } from '@/store/modules/user';
import { formatDate, parseDateToTimestamp, getTodayZeroTimestamp, getTomorrowZeroTimestamp } from '@/utils/formatTime'

const store = useUserStore();
const message = useMessage()
const toast = useToast()
const globalConfig = (getApp() as any).globalData.config;
const detailId = ref(null)  //页面详情id
const resubmit = ref(0)


// 指定审批人
const processDefineKey = 'oa_vehicleoutsourcing' // 流程定义 Key
const startUserSelectTasks = ref<any>([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref<any>({}) // 发起人选择审批人的数据
const startUserSelectAssigneesFormRules = ref<any>({}) // 发起人选择审批人的表单 Rules


const formFields = ref<any[]>([
	// { type: 'input', prop: 'driverName', label: '驾驶员姓名', placeholder: '请输入驾驶员姓名' },
	// { type: 'input', prop: 'driverPhonenumber', label: '驾驶员电话', placeholder: '请输入联系电话' },
	{ type: 'input', prop: 'sortOrder', label: '编号', placeholder: '保存时自动生成', readonly: true },
	{ type: 'input', prop: 'deptName', label: '用车部门', placeholder: '请输入用车部门' },
	{ type: 'input', prop: 'userId', label: '用车人', placeholder: '请输入用车人' },
	{ type: 'input', prop: 'userPhone', label: '用车人电话', placeholder: '请输入用车人电话' },
	{
		type: 'datetime',
		prop: 'startTime',
		label: '用车时间',
		placeholder: '请选择用车时间',
		datetimeType: 'datetime',
	},
	
	// { type: 'input', prop: 'carType', label: '车型', placeholder: '请输入车型' },
	// { type: 'input', prop: 'carNumber', label: '车号', placeholder: '请输入车号' },
	{ type: 'input', prop: 'drivingRoute', label: '行驶路线', placeholder: '请输入行驶路线' },
	// { type: 'input', prop: 'drivingKilometer', label: '行驶公里数', placeholder: '请输入行驶公里数' },
	// {
	// 	type: 'rate',
	// 	prop: 'serviceQty',
	// 	label: '服务质量评价',
	// },
	// {
	// 	type: 'datetime',
	// 	prop: 'startTime',
	// 	label: '开始日期',
	// 	placeholder: '请选择开始日期',
	// 	datetimeType: 'datetime',
	// },
	// {
	// 	type: 'datetime',
	// 	prop: 'endTime',
	// 	label: '结束日期',
	// 	placeholder: '请选择结束日期',
	// 	datetimeType: 'datetime',
	// 	get minDate() {
	// 		return typeof formData.value.startTime === 'number'
	// 			? formData.value.startTime
	// 			: Date.now();
	// 	},
	// 	get maxDate() {
	// 		return typeof formData.value.startTime === 'number'
	// 			? formData.value.startTime + 24 * 60 * 60 * 1000
	// 			: Date.now() + 24 * 60 * 60 * 1000;
	// 	}
	// },
	// {
	// 	type: 'input',
	// 	prop: 'cost',
	// 	label: '费用',
	// 	placeholder: '请输入费用',
	// 	inputType: 'number'
	// },
	{
		type: 'input',
		prop: 'driverRemark',
		label: '备注',
		placeholder: '请输入备注'
	}
])
const formData = ref<VehicleInCity.VehicLeOutVO>({
	userId: undefined, //用车人
	deptName: undefined, //用车部门
	userPhone: undefined, //用车人联系电话
	driverName: undefined, //驾驶人姓名
	driverPhonenumber: undefined, //驾驶人联系电话
	drivingKilometer: undefined, //行驶公里数
	drivingRoute: undefined, //行驶路线
	carNumber: undefined, //车号
	carType: undefined, //车型
	startTime: undefined, //开始日期
	endTime: undefined, //结束日期
	driverRemark: undefined, //驾驶人填写的备注
	serviceQty: 1, //服务质量评价
	cost: undefined, //费用
	sortOrder: undefined, //编号
} as any)
const headerObj = ref(
	{
		Authorization: 'Bearer ' + getAccessToken()
	}
)
const formRules = reactive({
	userId: [
		{
			required: true,
			message: '请输入用车人姓名',
			trigger: ['blur', 'change'],
		},
	],
	
	userPhone: [
		{ required: true, message: '用车人联系电话为数字', trigger: 'blur' },
		{
			pattern: /^1[3-9]\d{9}$|^(\+?\d{1,4}[-\s]?)?(\d{3,4}[-\s]?)?\d{7,8}$/
			,
			message: '请输入有效的电话号',
			trigger: ['blur', 'change'],
		},
	],
	driverName: [
		{
			required: true,
			message: '请输入驾驶员姓名',
			trigger: ['blur', 'change'],
		},
	],
	driverPhonenumber: [
		{
			required: true,
			message: '请输入驾驶员联系电话',
			trigger: ['blur', 'change'],
		},
		{
			pattern: /^1[3-9]\d{9}$|^(\+?\d{1,4}[-\s]?)?(\d{3,4}[-\s]?)?\d{7,8}$/
			,
			message: '请输入有效的电话号',
			trigger: ['blur', 'change'],
		},
	],
	deptName: [
		{
			required: true,
			message: '请输入用车部门',
			trigger: ['blur', 'change'],
		},
	],
	drivingRoute: [
		{
			required: true,
			message: '请输入行驶路线',
			trigger: ['blur', 'change'],
		},
	],
	drivingKilometer: [{ required: true, message: '请输入行驶公里数', trigger: 'blur' }],
	cost: [{ required: true, message: '费用为数字', trigger: 'blur' }],
	startTime: [{ required: true, message: '请选择开始日期', trigger: 'blur' }],
	endTime: [{ required: true, message: '请选择结束日期', trigger: 'blur' }]


})

onLoad(async (options) => {
	console.log('store',store);
	
	formData.value.userId=store.user.nickname
	formData.value.deptName=store.user.deptName
	const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
		undefined,
		processDefineKey
	)
	if (!processDefinitionDetail) {
		toast.error('流程模型未配置，请检查！')
		return
	}
	startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
	console.log('startUserSelectTasks', processDefinitionDetail)
	// 设置指定审批人
	if (startUserSelectTasks.value?.length > 0) {
		// 设置校验规则
		for (const userTask of startUserSelectTasks.value) {
			startUserSelectAssignees.value[userTask.id] = []
			startUserSelectAssigneesFormRules.value[userTask.id] = [
				{

					required: true,
					message: '请选择审批人',
					validator: (value: any) => {
						console.log("当前审批人值435435:", value); // 调试输出
						if (value && Array.isArray(value) && value.length > 0) {
							console.log('value.length', value.length);
							return Promise.resolve();
						} else {
							return Promise.reject('审批人不能为空');
						}
					},
					trigger: ['change']

				}
			]
		}
	}
	detailId.value = options?.id
	resubmit.value = options?.resubmit
	/** 获得详情 */
	if (detailId.value) { getDetailById() }
})


/** 获取页面详情 */
const getDetailById = async () => {
	try {
		const data = await VehicleInCity.getVehicLeOut(Number(detailId.value))
		formData.value = data
		if (formData.value.startTime) {
			formData.value.startTime = parseDateToTimestamp(formData.value.startTime)
		}
		if (formData.value.startTime) {
			formData.value.endTime = parseDateToTimestamp(formData.value.endTime)
		}
		console.log('formData.value', formData.value);
	} catch (error) {
		console.log('加载数据失败')
	}
}
/** 提交表单 */
const submitForm = async (payload: any) => {


	const { type, data } = payload
	console.log('type', type);
	console.log('data', data);
	try {
		if (type === 'update') {
			await VehicleInCity.updateVehicLeOut(data)
			toast.success('编辑成功');
		} else {
			data.type = 1
			await VehicleInCity.createVehicLeOut(data)
			toast.success('新增成功');
		}
		// 成功后跳转
		uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/vehicleoutsourcing/index' });
	} catch (error) {
		console.error('表单提交失败:', error);
		toast.error('提交失败，请稍后再试');
	}
}
/** 取消表单 */
const cancelForm = async () => {
	try {
		// 删除的二次确认
		await message.confirm({
			msg: '您确定要取消吗？',
			title: '提示'  // 添加标题
		})
		uni.navigateTo({ url: '/pagesPackage/OAsystemAutomation/vehicleoutsourcing/index' });
		// 显示成功提示
		toast.success('取消成功')
	} catch (error) {
		console.log('用户取消了操作或发生错误:', error)
	}
}
</script>

<style scoped lang="scss">
.container {
	padding: 20px 5px;
}

.custom-shadow {
	width: 40%;
	border-radius: 5%;
}
</style>